﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Xna.Framework;

namespace Jemgine.MapEditor
{
	class Camera
	{
		enum InputStates
		{
			Idle,
			Pan,
			Zoom
		}

		InputStates InputState = InputStates.Idle;

		Vector2 DragStart;
		Vector2 OldOffset;
		float OldZoom;

		public void MouseDown(MouseEventArgs Args, EditorState EditorState) 
		{
			if ((Control.ModifierKeys & Keys.Control) == Keys.Control)
			{
				OldZoom = EditorState.Camera.zoom;
				DragStart = new Vector2(Args.X, Args.Y);
				InputState = InputStates.Zoom;
			}
			else if (Control.ModifierKeys == 0)
			{
				OldOffset = EditorState.Camera.offset;
				DragStart = new Vector2(Args.X, Args.Y);
				InputState = InputStates.Pan;
			}
		}

		public void MouseMove(MouseEventArgs Args, EditorState EditorState) 
		{
			switch (InputState)
			{
				case InputStates.Idle:
					break;
				case InputStates.Pan:
					EditorState.Camera.offset = OldOffset;
					Vector2 Delta = (new Vector2(Args.X, Args.Y) - DragStart) / EditorState.Camera.zoom;
					Delta.Y *= -1;
					EditorState.Camera.offset += Delta;
					EditorState.OnInvalidateMap();
					break;
				case InputStates.Zoom:
					Delta = new Vector2(Args.X, Args.Y) - DragStart;

					float Length = Delta.Length();
					if (Delta.Y > 0) Length *= -1;
					Length *= 0.01f;

					EditorState.Camera.zoom = OldZoom + Length;

					if (EditorState.Camera.zoom < 1.0f) EditorState.Camera.zoom = 1.0f;
					if (EditorState.Camera.zoom > 32.0f) EditorState.Camera.zoom = 32.0f;
					EditorState.OnInvalidateMap();
					break;
				default:
					throw new InvalidProgramException();
			}
		}

		public void MouseUp(MouseEventArgs Args) 
		{
			InputState = InputStates.Idle;
		}
	}
}
